<template>
  <div>
    <el-form
      ref="ruleForm"
      size="small"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      label-position="left"
      :disabled="disabled"
    >
      <el-card class="box">
        <div class="box">
          <el-form-item
            label="选择客户"
            prop="custNo"
          >
            <el-input
              readonly
              v-model="ruleForm.custName"
              placeholder="请选择客户"
              @click.native="handleInputClick"
              suffix-icon="el-icon-edit"
              style="width: 200px;"
            ></el-input>
          </el-form-item>
        </div>
        <div
          class="box"
          v-if="ruleForm.scoreConlusuin.length"
        >
          <div class="title">评分细则</div>
          <div
            v-for="(item, index) in ruleForm.scoreConlusuin"
            :key="index"
          >
            <div style="background-color: #E8F3FC; padding: 10px; border-radius: 2px; font-size: 12px; margin-bottom: 20px;">
              <div style="margin-bottom: 10px;">
                <i
                  class="el-icon-warning"
                  style="color: #1386DE;"
                ></i>
                {{ item.scoreName || '' }}
              </div>
              <div style="padding-left: 15px;">
                <span style="color: #4BA3E6;">计算公式：</span>
                <span style="color: #979EA4;">{{ item.scoreAccord || '' }}</span>
              </div>
            </div>
            <el-table
              :data="item.fileInfos"
              style="width: 100%; margin-bottom: 20px"
              border
            >
              <el-table-column
                label="序号"
                width="80"
              >
                <template slot-scope="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column
                label="附件名称"
                prop="fileName"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.fileName"
                    placeholder="请输入附件名称"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="附件说明"
                prop="fileDesc"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.fileDesc"
                    placeholder="请输入附件说明"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="附件上传"
                prop="fileDesc"
              >
                <template slot-scope="scope">
                  <el-upload
                    class="upload-demo"
                    :ref="'uploadFile' + index  + '_' + scope.$index"
                    :accept="fileAccept"
                    :action="uploadFileUrl + '/file/saveFile'"
                    :before-upload="beforeUpload"
                    :on-change="(file, fileList) => handleChange(file, fileList, scope.row)"
                    :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, scope.row, scope.$index, 'uploadFile' + index  + '_' + scope.$index)"
                    :on-remove="(file, fileList) => handleRemove(file, fileList, scope.row)"
                    :file-list="scope.row.fileList"
                    :data="{fileRemark: scope.row.fileDesc, fileuserInfo: scope.row.fileName}"
                    :multiple="false"
                    :auto-upload="true"
                  >
                    <el-button
                      type="text"
                      style="font-size: 16px;"
                      icon="el-icon-upload2"
                    ></el-button>
                  </el-upload>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="150px"
              >
                <template
                  slot="header"
                  slot-scope="scope"
                >
                  操作
                  <el-button
                    size="mini"
                    type="primary"
                    v-if="!disabled"
                    style="margin-left: 10px;"
                    @click="addFileList(index)"
                  >+新增</el-button>
                </template>
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    v-if="!disabled"
                    style="color: red;"
                    @click="deleteFileList(index, scope.$index)"
                  >删除</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    :disabled="!disabled"
                    v-if="disabled"
                    @click="handleDownloadFile(scope.row)"
                  >下载</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    :disabled="!disabled"
                    v-if="disabled"
                    @click="handlePreviewFile(scope.row)"
                  >预览</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row :gutter="10">
              <el-col :span="6" class="label-top">
                <el-form-item
                  label="本项评分"
                  :prop="'scoreConlusuin.' + index + '.score'"
                  :rules="{ required: handleRequiredFile(item), message: '本项评分不能为空', trigger: 'blur' }"
                >
                  <el-input-number
                    v-model="item.score"
                    controls-position="right"
                    :min="0"
                    :max="item.maxScore"
                    :style="{width: '100%'}"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="18" class="label-top">
                <el-form-item
                  label="评分结论"
                  :prop="'scoreConlusuin.' + index + '.creditConclusion'"
                  :rules="{ required: handleRequiredFile(item), message: '评分结论不能为空', trigger: 'blur' }"
                >
                  <el-input
                    v-model="item.creditConclusion"
                    placeholder="请输入评分结论"
                    clearable
                    :style="{width: '100%'}"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <div style="margin: 20px 0; background-color: #DEDEDE; height: 1px; width: 100%;"></div>
          </div>
        </div>
        <div
          class="box"
          v-if="tableData.length"
        >
          <div class="title">授信额度提示</div>
          <el-table
            :data="tableData"
            style="width: 100%; margin-bottom: 20px"
            border
            height="200"
          >
            <el-table-column
              prop="creditScore"
              label="客户信用评分"
              :show-overflow-tooltip="true"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="creditLevel"
              label="客户信用等级"
              :show-overflow-tooltip="true"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="creditFactor"
              label="信用系数"
              :show-overflow-tooltip="true"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="creditLimit"
              label="信用额度（万元）"
              :show-overflow-tooltip="true"
              min-width="150"
            >
              <template slot-scope="scope">
                {{ formatReceiveAmount(scope.row.creditLimit / 10000) }}
              </template>
            </el-table-column>
          </el-table>
          <el-form
            size="small"
            label-position="top"
            style="margin-bottom: 10px;"
          >
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item
                  label="本次拟授信额度"
                  prop="creditLimit"
                >
                  <el-input
                    v-model.number="ruleForm.creditLimit"
                    placeholder="请输入本次拟授信额度"
                    :style="{width: '100%'}"
                    type="number"
                    :disabled="disabled && !options.docPermission.priceEdit"
                    min="0"
                    @blur="handleBlur($event, 'creditLimit')"
                  >
                    <template slot="append">万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item
                  label="本次评分结论"
                  prop="totalConlusuin"
                >
                  <el-input
                    v-model="ruleForm.totalConlusuin"
                    placeholder="请输入本次评分结论"
                    clearable
                    :disabled="disabled"
                    type="textarea"
                    :rows="2"
                    :style="{width: '100%'}"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div style="width: 100%; padding: 10px; background-color: #EEEEEE; border-radius: 2px;">
            <span style="margin-right: 10px;">综合评分：{{ handleTotalScore() }}分</span>
            <span>(信用等级{{ handleCreditLeve('creditLevel') }},系数{{ handleCreditLeve('creditFactor') }})</span>
          </div>
        </div>
      </el-card>
      <el-card v-if="!disabled">
        <div>
          <el-form-item
            label="下一节点审批人"
            prop="targetUserName"
            label-width="120px"
          >
            <el-radio-group v-model="ruleForm.targetUserName">
              <el-radio
                :label="item.userName"
                v-for="item in approveList"
                :key="item.userName"
              >{{ item.nickName }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div>
          <el-button
            type="info"
            size="mini"
            @click="handleSubmit('0')"
          >保存草稿</el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleSubmit('1')"
          >确认提交</el-button>
        </div>
      </el-card>
    </el-form>

    <CustomTable
      :templateName="templateName"
      :queryData="queryData"
      ref="customTableRef"
      @ok="handleOk"
    ></CustomTable>

    <PreviewFile
      :fileType="fileType"
      :fileUrl="fileUrl"
      :dialogVisible="dialogFileVisible"
      @cancel="dialogFileVisible = false"
    />
  </div>
</template>

<script>
import { getNodeUsers, customerList, listScore, listCreditLevel, customerInfo } from '@/api/processManage/approveForms'
import { downloadFile, previewFile, formatMoney } from '@/utils/utils';

import PreviewFile from '@/components/PreviewFile/index'

import CustomTable from "./CustomTable"
export default {
  dicts: ['enabled_file_upload_types'],
  props: ['templateId', 'doc', 'flowNo', 'disabled', 'options', 'templateName'],
  components: {
    CustomTable,
    PreviewFile
  },
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API,
      ruleForm: {
        custName: '',
        custNo: '',

        creditScoreId: '',
        approveId: '',
        totalConlusuin: '',
        creditLimit: '',
        status: '',
        targetUserName: '',
        flag: '0',
        scoreConlusuin: []
      },
      rules: {
        custNo: [{ required: true, message: '请选择客户', trigger: 'change' }],
        totalConlusuin: [{ required: true, message: '请输入本次评分结论', trigger: 'blur' }],
        creditLimit: [{ required: true, message: '请输入本次拟授信额度', trigger: 'blur' }],
        targetUserName: [{ required: true, message: '请选择下一节点审批人', trigger: 'blur' }],
      },
      approveList: [],
      tableData: [],
      scoreConlusuin: [],
      fileAccept: '',

      fileUrl: '',
      fileType: '',
      dialogFileVisible: false,
      queryData: {},
    }
  },
  created() {
    this.$nextTick(() => {
      this.$refs['ruleForm'].resetFields();
    })
    this.handleGetNodeUsers()
    this.handlelistCreditLevel()
  },
  watch: {
    doc: {
      handler(val) {
        if (JSON.stringify(val) !== '{}') {
          let params = JSON.parse(JSON.stringify(val))
          this.ruleForm = {
            ...params,
            // custName: '',
            creditLimit: Number((params.creditLimit / 10000).toFixed(4))
          };

          if (params.scoreConlusuin) {
            if (params.scoreConlusuin.length > 0) {
              this.ruleForm.scoreConlusuin = params.scoreConlusuin.map(item => ({
                ...item,
                fileInfos: item.fileInfos.map(v => ({
                  ...v,
                  fileList: v.fileName ? [{ name: v.fileName }] : [],
                })),
              }));
            } else {
              this.ruleForm.scoreConlusuin = []
              this.handleListScore()
            }
          } else {
            this.ruleForm.scoreConlusuin = []
            this.handleListScore()
          }

          this.handleListCustomerAdmit();
        }
      },
      deep: true
    },
    'dict.type.enabled_file_upload_types': {
      deep: true,
      handler(newValue) {
        if (newValue && newValue.length > 0) {
          this.fileAccept = newValue.map(item => {
            let updatedValue = item.value.split(',').map(item => `.${item}`).join(',');
            return updatedValue;
          }).join(',');
        }
      },
      immediate: true,
    }
  },
  methods: {
    formatReceiveAmount(amount) {
      return formatMoney(amount);
    },
    handleRequiredFile(item) {
      return item.fileInfos.some(v => v.fileList.length > 0)
    },
    handleCreditLeve(type) {
      for (let i = 0; i < this.tableData.length; i++) {
        let min = this.tableData[i].creditScore.split('-')[0]
        let max = this.tableData[i].creditScore.split('-')[1]
        if (this.handleTotalScore() >= min && this.handleTotalScore() <= max) {
          return this.tableData[i][type]
        }
        if (i==this.tableData.length-1 && this.handleTotalScore() > max) {
          return this.tableData[i][type]
        }
      }
    },
    handlelistCreditLevel() {
      listCreditLevel().then(res => {
        this.tableData = res.rows
      })
    },
    handleListCustomerAdmit() {
      customerInfo({ customerId: this.ruleForm.custNo }).then(res => {
        // this.ruleForm.custName = res.data.customerName
        this.ruleForm.customerType = res.data.customerType
      })
    },
    handleGetNodeUsers() {
      getNodeUsers({
        templateId: this.templateId,
        flowNo: '',
        targetAction: 'TO_NEXT',
        targetNodeId: ''
      }).then(res => {
        this.approveList = res.data
        this.ruleForm.targetUserName = res.data.length ? res.data[0].userName : ''
      })
    },
    handleTotalScore() {
      let totalScore = 0;
      for (let i = 0; i < this.ruleForm.scoreConlusuin.length; i++) {
        totalScore += Number(this.ruleForm.scoreConlusuin[i].score);
      }
      return totalScore;
    },
    handleBlur(e, type) {
      this.ruleForm[type] = e.target.valueAsNumber < 0 ? 0 : e.target.valueAsNumber.toFixed(4)
    },
    beforeUpload(file) {
      if (file.size / 1024 / 1024 > 50) {
        this.$message.error('文件不能超过50M！');
        return false;
      }
      return true;
    },
    handleChange(file, fileList, v) {
      if (fileList.length > 0) {
        v.fileList = [fileList[fileList.length - 1]];
      } else {
        v.fileList = [];
      }
      return true
    },
    handleSuccess(response, file, fileList, v, i, uploadName) {
      let uid = file.uid
      let idx = this.$refs[uploadName][0].uploadFiles.findIndex(item => item.uid == uid)
      if (response.code != 200) {
        this.$modal.msgError('文件格式或命名存在特殊字符,请检查后重新上传!');
        this.$refs[uploadName][0].uploadFiles.splice(idx, 1)
        return true;
      }

      const { fileName: originalFileName, fileUuid } = response.data;
      v.fileName = originalFileName.split('.').shift();
      v.fileId = fileUuid;
      v.fileList.push(file);
    },
    handleRemove(file, fileList, v) {
      v.fileList = fileList
      if (!v.fileList.length) {
        v.fileId = ''
        v.fileName = ''
      }
      // v.fileList = fileList.filter(item => item !== file);
    },
    addFileList(index) {
      this.ruleForm.scoreConlusuin[index].fileInfos.push({
        fileDesc: '',
        fileId: '',
        fileName: '',
        fileList: []
      })
    },
    // 删除附件列表
    deleteFileList(index, i) {
      this.ruleForm.scoreConlusuin[index].fileInfos.splice(i, 1);
    },
    handleListScore() {
      listScore({
        customerId: this.ruleForm.customerId,
        scoreIds: this.ruleForm.customerId,
        custType: this.ruleForm.customerType,
        flag: '0',
        option: '01',
        status: '01'
      }).then(res => {
        this.ruleForm.scoreConlusuin = res.data.score.map(item => {
          return {
            ...item,
            creditConclusion: '',
            score: '',
            fileInfos: [],
            scoreId: item.creditScoreId
          }
        })
      })
    },
    handleInputClick() {
      if (!this.disabled) {
        this.$refs.customTableRef.sync()
      }
    },
    handleOk(row) {
      this.ruleForm.custName = row.customerName
      this.ruleForm.custNo = row.customerId
      this.ruleForm.customerType = row.customerType
      this.handleListScore()
    },
    async validateFields(fields, formRef) {
      const validationPromises = fields.map(field => {
        return new Promise((resolve, reject) => {
          formRef.validateField(field, (errorMessage) => {
            if (!errorMessage) {
              resolve();
            }
          });
        });
      });

      try {
        await Promise.all(validationPromises);
      } catch (error) {
        throw error;
      }
    },

    handleSubmit(flag) {
      this.ruleForm.flag = flag
  
      let creditLeveIds = this.tableData.map(item => item.id);
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.$emit('submit', {
            ...this.ruleForm,
            flag,
            creditLimit: Number((this.ruleForm.creditLimit * 10000).toFixed(2)),
            totalScore: this.handleTotalScore(),
            creditLeveIds: creditLeveIds.join(','),
            flowNo: this.flowNo || ''
          });
        } else {
          return false
        }
      })
    },
    // 文件下载
    async handleDownloadFile(row) {
      downloadFile({ fileUuid: row.fileId });
    },
    // 文件预览
    async handlePreviewFile(row) {
      try {
        const { arrayBuffer, fileType } = await previewFile({ fileUuid: row.fileId });
        this.fileUrl = arrayBuffer;
        this.fileType = fileType;
        this.dialogFileVisible = true
      } catch (error) {
        this.$modal.msgError(error.message);
      }
    },

  }
}
</script>
<style lang="scss" scoped>
.box {
  margin-bottom: 20px;
  .title {
    margin-bottom: 10px;
    font-size: 14px;
    font-weight: bold;
  }
  .box-card {
    margin-bottom: 20px;
  }

  .upload-demo {
    display: flex;
    align-items: center;
    :deep(.el-upload-list) {
      width: 90%;
      .el-upload-list__item {
        margin-top: 0 !important;
      }
    }
  }
}
.label-top {
  :deep(.el-form-item) {
    display: flex;
    flex-direction: column;
  }
  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}
</style>
